var FG;
if (!FG)
    FG = {};

FG.ProjectMapConnection = function(opts) {
    var this_ = this;
    
    this.moduleInfo = {
        name: 'projectMapConnection',
        zhName: '工程与地图连接',
        desc: '工程与地图连接'
    };
    
    this.app = opts.app;
    
    this.connectSignals();
};

FG.ProjectMapConnection.prototype.connectSignals = function() {
    var this_ = this,
        app = this.app,
        projectCore = app.getModule('projectCore'),
        projectPanel = app.getModule('projectPanel'),
        mapPanel = app.getModule('mapPanel');


    app.toolModer.registerMode('project', 
        function() {
            mapPanel.showFeatureGroup('pitem');
        },
        function() {
            mapPanel.hideFeatureGroup('pitem');
        }
    );
    
    DX.on('db:pitem:add', function(pitem) {
        if (pitem.get('item_type') === 'MultiPolygon') {
            if (!pitem.has('hasMapData') || !pitem.get('hasMapData')) {
                return;
            }
        }
        // push or not push, based on showing status?
        mapPanel.pushFeature('pitem', pitem);
    });

    DX.on('db:pitem:update', function(pitem){
        var changed = pitem.changedAttributes();
        var bigChanges = _.omit(changed, 'create_dt', 'access_dt', 'modify_dt');
        if (!changed || _.isEmpty(bigChanges))
            return;
        // TODO: 会发来两次更新名字的信息。
        //if (_.contains(['Point', 'Rect'], opts.get('item_type'))) {
        //    this_.userFeatureGroupView.pushEntry(opts);
        //} else {
        //    this_.linePolyFeatureGroupView.pushEntry(opts);
        //}
        if (pitem.get('item_type') === 'MultiPolygon') {
            if (!pitem.has('hasMapData') || !pitem.get('hasMapData')) {
                return;
            }
        }
        mapPanel.pushFeature('pitem', pitem);
    
        //var featureView = this_.userFeatureGroupView.getByTag(opts.getTag());
    });

    DX.on('db:pitem:del', function(pitem){
        mapPanel.delFeature('pitem', pitem);
    });

    DX.on('db:project:switch', function(project) {
        mapPanel.clearFeatures('pitem');
        if (!project) {
            return;
        }
        if (_.has(project, 'itemList')){
            project.itemList.each(function(item) {
                mapPanel.pushFeature('pitem', item)
            })
        }
    });

    DX.on('db:snapshot:switch', function(snapshot) {
        mapPanel.switchSnapshot(snapshot);
    });

    DX.on('viewport:switch!', function(viewport) {
        if (!viewport)
            return;
    
        if (_.contains(['pitem', 'dsv', 'snapshot'], viewport.type)) {
            // if (!!this.currentFeatureView) {
            //     this.currentFeatureView.setFocus(false);
            // }
            var pitemUUID = viewport.status.pitem;
            _.each(mapPanel.getFeatureGroupView('pitem').entryList, function(featureView) {
                var uuid = featureView.getTag();
                if (uuid !== pitemUUID) {
                    featureView.setFocus(false);
                } else {
                    featureView.setFocus(true);
                
                    if (_.has(viewport.status, 'coords')) {
                        featureView.widget.switchViewport(viewport);
                    }
                    mapPanel.currentFeatureView = featureView;
                }
            });
        } else if (viewport.type === 'map') {
        
        }
    });

    // 地图feature相关
    DX.on('feature:drawn', function(info) {
        if (app.toolModer.currentMode === 'project') {
            if (!!info.geometry) {
                if (info.geometry.type === 'Point') {
                    _.extend(info, {dbtype: 'pitem'});
                    mapPanel.pushDBFeature(info)
                } else if (info.geometry.type === 'Polygon') {
                    DX.prompt('请输入此区域的名字 <span style="font-size: 12px">(将保存至用户地图数据库)</span>', '', function (name) {
                        var uuid = DX.gen_uuid12();
                        var feature = {
                            type: 'Feature',
                            dbtype: 'pitem',
                            geometry: {
                                type: 'Polygon',
                                coordinates: info.geometry.coordinates
                            },
                            properties: {
                                uuid: uuid,
                                name: name
                            },
                            focus: true
                        };
        
                        DX.once('feature:rendered', _.debounce(function (featureView) {
                            featureView.setFocus(true);
                            mapPanel.map.fitBounds(featureView.feature.getBounds(), {
                                padding: [300, 50]
                            });
                        }, 50));
        
                        mapPanel.pushDBFeature(feature);
                    })
                } else {
                    DX.error('工程模块暂时不支持这种类型的地物: '+info.geometry.type)
                }
            } else {
                _.extend(info, {dbtype: 'pitem'});
                mapPanel.pushDBFeature(info)
            }
        }
    });

    DX.on('dbfeature:push!', function(opts) {
        if (app.toolModer.currentMode === 'project') {
            projectCore.pushPItem(opts);
        }
    });

    // 地图搜索相关
    DX.on('search:point:located', function(info) {
        if (app.toolModer.currentMode !== 'project') {
            return;
        }
        var zoom;
        if (info.action === 'goto') {
            zoom = !!info.result.zoom ? info.result.zoom : 10;
            if (!!info.result.center) {
                mapPanel.goTo([info.result.center.lat, info.result.center.lon], zoom);
            }
        } else {
            //TODO ...
            var uuid = DX.gen_uuid12(),
                c = info.result.center;
            var feature = {
                // TODO: 当扩展到支持别的模块时, 需要指定feature的dbtype为别的.
                dbtype: 'pitem',
                type: 'Point',
                center: c,
                properties: _.extend({uuid: uuid},
                    _.omit(
                        info.result,
                        'geometry', 'center'
                    )
                ),
                focus: true
            };
        
            zoom = !!info.result.zoom ? info.result.zoom : 10;
            DX.once('feature:rendered', _.debounce(function(featureView) {
                featureView.setFocus(true);
                if (!!c) {
                    mapPanel.goTo([c.lat, c.lon], zoom);
                }
            }, 50));
        
            mapPanel.pushDBFeature(feature);
        }
    });

    DX.on('search:polygon:located', function(info) {
        if (app.toolModer.currentMode !== 'project') {
            return;
        }
        var uuid = DX.gen_uuid12(),
            geometry = info.result.geometry;
        var feature = {
            // TODO: 当扩展到支持别的模块时, 需要指定feature的dbtype为别的.
            dbtype: 'pitem',
            properties: _.extend({uuid: uuid},
                _.omit(
                    info.result,
                    'geometry'
                )
            ),
            focus: true
        };
    
        if (!!geometry) {
            feature.type = 'Feature';
            feature.geometry = info.result.geometry
        } else {
            feature.type = 'UriFeature';
            if (!!info.result.uri) {
                feature.geometry_uri = info.result.uri;
            } else if (!!info.result.adcode) {
                feature.geometry_uri = 'ad:' + info.result.adcode;
            }
        }
    
        DX.once('feature:rendered', _.debounce(function(featureView) {
            featureView.setFocus(true);
            mapPanel.map.fitBounds(featureView.feature.getBounds(), {
                padding: [300, 50]
            });
        }, 50));
    
        mapPanel.pushDBFeature(feature);
    });

    DX.on('search:line:located', function(info) {
    
    });
    
    DX.on('map:feature:clicked', function(feature) {
        if (_.contains(['PointMarker', 'RectFeature', 'PolygonFeature'], feature.className)) {
            var uuid = feature.getTag();
            projectPanel.focusPItem(uuid);
        }
    });
};

